package com.aiwhose.aiwhosesecurity.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.aiwhose.aiwhosecore.bean.Result;
import com.aiwhose.aiwhosecore.bean.security.ShortMessage;
import com.aiwhose.aiwhosecore.bean.security.User;
import com.aiwhose.aiwhosesecurity.service.ShortMessageService;
import com.aiwhose.aiwhosesecurity.service.UserService;
import com.aiwhose.aiwhosesecurity.utils.LineCaptcha;
import com.aiwhose.aiwhosesecurity.utils.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/webUser")
public class WebUserController {


    @Resource
    UserService userService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ShortMessageService shortMessageService;


    // 查询登录状态，浏览器访问
    @GetMapping("/isLogin")
    public Result isLogin() {
        if (StpUtil.isLogin()) {
            return Result.ok();
        } else {
            return Result.ok(null, "用户未登录", 401);
        }
    }


    //获取图片验证码
    @PostMapping("/getImgVerify")
    @ResponseBody
    public Result getImgVerify(@RequestBody User user) throws FileNotFoundException {
        LineCaptcha lineCaptcha = new LineCaptcha();
//        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(180, 60);
        String imgCode = lineCaptcha.getImgCode(user.getPhone(), redisUtil);
        return Result.ok("data:image/png;base64," + imgCode, "");
    }

    //发送验证码
    @PostMapping("/sendSMS")
    @ResponseBody
    public Result sendSMS(@RequestBody ShortMessage shortMessage) throws UnsupportedEncodingException {
        String phone = shortMessage.getPhone();
        String imgCode = shortMessage.getImgCode();
        if (!new LineCaptcha().checkVerify(phone, imgCode, redisUtil)) {
            return Result.error("图形验证码错误");
        }
        if (ObjectUtil.isNotEmpty(redisUtil.get("SECURITY:SMS:SHORTMESSAGE:" + phone))) {
            return Result.error("5分钟内只能获取一次验证码！");
        }
        String randomNumber = RandomUtil.randomNumbers(6);
        String content = URLEncoder.encode("验证码：" + randomNumber.trim() + "，打死都不要告诉别人哦！", "GBK");

        Boolean senfResult = shortMessageService.sendSMS(content, phone);

        if (senfResult) {
            boolean set = redisUtil.set("SECURITY:SMS:SHORTMESSAGE:" + phone, randomNumber, 5L * 60);
            return Result.ok("验证码发送成功！");
        } else {
            return Result.ok("验证码发送失败！");
        }

    }

    //校验验证码
    @PostMapping("/checkSMS")
    @ResponseBody
    public Result checkSMS(@RequestBody ShortMessage shortMessage) throws UnsupportedEncodingException {
        String phone = shortMessage.getPhone();
        String code = shortMessage.getImgCode();
        Object imageCode = redisUtil.get("SECURITY:SMS:SHORTMESSAGE:" + phone);
        if (ObjectUtil.isNotEmpty(imageCode)) {
            boolean equals = StrUtil.equals(code, imageCode.toString());
            if (equals) {
                return Result.ok("验证码正确！");
            }
            return Result.error("验证码失效！");
        }

        return Result.error("验证码失效！");

    }

    //验证码登录
    @PostMapping("/smsLogin")
    @ResponseBody
    public Result smsLogin(@RequestBody User user) {
        String phone = user.getPhone();
        String imgCode = user.getImgCode();
        String smsCode = user.getSmsCode();
        if (!new LineCaptcha().checkVerify(phone, imgCode, redisUtil)) {
            return Result.error("图形验证码错误");
        }
        Object imageCode = redisUtil.get("SECURITY:SMS:SHORTMESSAGE:" + phone);
        if (ObjectUtil.isNotEmpty(imageCode)) {
            boolean equals = StrUtil.equals(smsCode, imageCode.toString());
            if (!equals) {
                return Result.error("验证码错误！");
            }
        } else {
            return Result.error("验证码失效！");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getSystemType, "AIWHOSE-GROUP");
        queryWrapper.eq(User::getPhone, phone);
        User userByPhone = userService.getOne(queryWrapper);
        if (BeanUtil.isEmpty(userByPhone)) {
            return Result.error("账号不存在，请注册");
        }
        StpUtil.login(userByPhone.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        userByPhone.setSalt("");
        userByPhone.setPassword("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("tokenInfo", tokenInfo);
        map.put("userInfo", userByPhone);
        return Result.ok(map);


    }
    /*

    //密码登录
    @PostMapping("/passwordLogin")
    @ResponseBody
    public Map<String, Object> passwordLogin(@RequestBody Map<String, Object> body) {
        String phone = MapUtil.get(body, "phone", String.class, "");
        String password = MapUtil.get(body, "password", String.class, "");
        String imgCode = MapUtil.get(body, "imgCode", String.class, "");

        if (!new LineCaptcha().checkVerify(phone, imgCode, redisUtil)) {
            return Result.error("图形验证码错误");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(UserSms::getPhone, phone);
        User userByPhone = userService.getUserByPhone(phone,"aiwhose");
        if (userByPhone != null) {
            String passwordMD5 = DigestUtil.md5Hex(userByPhone.getSalt() + password);
            if (StrUtil.isEmptyIfStr(userByPhone.getPassword())) {
                return Result.error(Result.ERROR_500, "未设置密码，请验证码登录");
            }
            if (userByPhone.getPassword().equals(passwordMD5)) {
                StpUtil.login(userByPhone.getId());
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                StpInterfaceImpl stpInterface = new StpInterfaceImpl();
                List<String> permissionList = stpInterface.getPermissionList(userByPhone.getId(), "");
                userByPhone.setSalt("");
                userByPhone.setPassword("");
                HashMap<String, Object> map = new HashMap<>();
                map.put("tokenInfo", tokenInfo);
                map.put("permissionList", permissionList);
                map.put("user", userByPhone);
                return Result.ok(map, "登陆成功！");
            } else {
                return Result.error(Result.NO_AUTH_401, "密码错误！");
            }

        } else {
            return Result.error(Result.ERROR_500, "用户不存在！");
        }


    }


    //设置密码
    @SaCheckLogin
    @PostMapping("/setPassword")
    @ResponseBody
    public Map<String, Object> setPassword(@RequestBody Map<String, Object> body) {
        if (StpUtil.isLogin()) ;
        String loginId = StpUtil.getLoginId().toString();
        String phone = MapUtil.get(body, "phone", String.class, "");
        String password = MapUtil.get(body, "password", String.class, "");
        String imgCode = MapUtil.get(body, "imgCode", String.class, "");
        String smsCode = MapUtil.get(body, "smsCode", String.class, "");
        if (!new LineCaptcha().checkVerify(phone, imgCode, redisUtil)) {
            return Result.error(Result.ERROR_500, "图形验证码错误");
        }
        if (!userSmsService.checkSMS(phone, smsCode)) {
            return Result.error(Result.NO_AUTH_401, "短信验证码错误");
        }
        User userByPhone = userService.getById(loginId);
        if (userByPhone == null) {
            return Result.error(Result.ERROR_500, "用户不存在！");
        }

        String salt = NumberUtils.getNumber6();
        userByPhone.setSalt(salt);
        userByPhone.setPassword(DigestUtil.md5Hex(salt + password));
        boolean updateUser = userService.updateById(userByPhone);
        if (updateUser) {
            return Result.ok("密码修改成功！");
        }
        return Result.error("密码修改失败！");
    }*/
}
